﻿@inject IHttpService _httpService

@inject NavigationManager NavigationManager
@inject IJSRuntime JS
@inject IDataCacheService _dataCatcheService
@inject IPopupService PopupService

@implements IDisposable

@if (string.IsNullOrWhiteSpace(Model.Name) == false)
{
    <CnGalWebSite.Shared.MasaComponent.Shared.Cards.TitleTip Title="@(Model.Name)" Description="@Model.BriefIntroduction" Image="@Model.MainPicture" />
}
else
{
    <CnGalWebSite.Shared.MasaComponent.Shared.Cards.TitleTip />
}
@if (_dataCatcheService.ThemeSetting.IsTransparent)
{
    @if (string.IsNullOrWhiteSpace(Model.SmallBackgroundPicture) == false)
    {
        <div id="web_bg" style="background-image: url(@Model.SmallBackgroundPicture)" class=" d-none  bg-d-lg-block bgimage-ison"></div>
    }
    @if (string.IsNullOrWhiteSpace(Model.BackgroundPicture) == false)
    {
        <div id="web_bg" style="background-image: url(@Model.BackgroundPicture)" class=" d-none d-sm-block bgimage-ison"></div>
    }
}


@if (isNotFound == true)
{
    <NotFoundCard>
        <h1 class="text-center title-large">找不到这个周边哦......</h1>
        <div class="text-center">可以在这里<a href="/peripheries/createperiphery">创建周边</a>，也可以查看<a href="/articles/index/253">《周边编辑规范》</a></div>
    </NotFoundCard>
}
else
{
    @if (_dataCatcheService.PeripheryIndexPageCatche.Check(Id) || isReady)
    {
        <div class="row">
            <div class="col-12 mb-4">
                @if (Model.IsHidden == true)
                {
                    <CnGalWebSite.Shared.MasaComponent.Shared.Components.MasaAlert Type="AlertTypes.Warning" Class="mb-3">
                        当前周边处于隐藏状态，如果你看到了这个提示，请立即联系管理员
                    </CnGalWebSite.Shared.MasaComponent.Shared.Components.MasaAlert>

                }
                <PeripheryMainInforTip Model="Model" OnRevoke="OnRevoke" OnPreEdit="OnPreEdit" CollectionChanged="CollectionChanged" />
            </div>


            @if (_dataCatcheService.IsApp)
            {
                <div class="col-12 col-lg-4 ">

                    <PeripheryBasicInforTip Model="Model" OnRevoke="OnRevoke" />
                </div>
                <div class="col-12 col-lg-8">
                    @if (Model.Pictures.Count != 0)
                    {
                        <div class="mb-3">
                            <PeripheryImagesViewTip Model="Model" OnRevoke="OnRevoke" />
                        </div>
                    }
                    <CnGalWebSite.Shared.MasaComponent.PC.FavoriteFolders.CatalogsCard Type="FavoriteObjectType.Periphery" Id="Model.Id" />
                    <PeripheryListOverviewsTip Model="Model" @ref="appPeripheryOverViewTip" OnRevoke="OnRevoke" />

                    <CnGalWebSite.Shared.MasaComponent.PC.Comments.CommentTip CanComment="Model.CanComment" CanDeleted="IsAdmin" ObjectId="@Model.Id.ToString()" Type="CommentType.CommentPeriphery" />
                </div>
            }
            else
            {

                <div class="col-12 col-lg-8  order-2 order-lg-1">
                    @if (Model.Pictures.Count != 0)
                    {
                        <PeripheryImagesViewTip Model="Model" OnRevoke="OnRevoke" />
                    }

                    <PeripheryListOverviewsTip Model="Model" @ref="peripheryOverViewTip" OnRevoke="OnRevoke" />


                    <CnGalWebSite.Shared.MasaComponent.PC.Comments.CommentTip CanComment="Model.CanComment" CanDeleted="IsAdmin" ObjectId="@Model.Id.ToString()" Type="CommentType.CommentPeriphery" />

                </div>

                <div class="col-12 col-lg-4 order-1 order-lg-2">

                    <PeripheryBasicInforTip Model="Model" OnRevoke="OnRevoke" />
                    <PeripheryListRelevancesViewTip Model="Model" />
                    <CnGalWebSite.Shared.MasaComponent.PC.FavoriteFolders.CatalogsCard Type="FavoriteObjectType.Periphery" Id="Model.Id" />
                </div>
            }
        </div>

    }
    else
    {

        <CnGalWebSite.Components.Progressings.ProgressingCard Page />
    }
}

<CnGalWebSite.Shared.MasaComponent.Shared.Components.TrackEvent DataType="TrackEventDataType.Periphery" EventType="TrackEventType.View" ObjectId="@Model.Id.ToString()"
                                                                ObjectName="@Model.Name" />
@if (isFirstLoad == false)
{
    <CnGalWebSite.Shared.MasaComponent.Shared.Cards.NavLoadingCard IsLoading="isLoading" />
}



@code {
    [Parameter]
    public string Id { get; set; }
    public string steam { get; set; }
    public string MainPageHtml { get; set; }
    public int currentPage { get; set; } = 1;
    public string NoticeCard { get; set; } = "";
    public string CurrentUserRank { get; set; }
    bool isReady = false;
    bool isNotFound = false;
    bool isAsyncReady = false;
    bool isLoading = false;
    bool isFirstLoad = true;

    public PeripheryViewModel Model { get; set; } = new PeripheryViewModel();

    public PagedResultDto<CommentViewModel> ListComments = new PagedResultDto<CommentViewModel> { Data = new List<CommentViewModel>(), CurrentPage = 1, TotalCount = 0 };

    public bool IsUserFavorited { get; set; }
    public FavoriteFolderOverviewModel UserFavoriteInfor { get; set; }
    private PeripheryListOverviewsTip peripheryOverViewTip;
    private PeripheryListOverviewsTip appPeripheryOverViewTip;

    public bool IsAdmin { get; set; } = false;
    string LastLookName = "";
    bool isFrist = true;

    [CascadingParameter]
    private Task<AuthenticationState> authenticationStateTask { get; set; }

    [CascadingParameter]
    public ErrorHandler ErrorHandler { get; set; }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await base.OnAfterRenderAsync(firstRender);
        if (firstRender)
        {
            NavigationManager.LocationChanged -= LocationChanged;
            NavigationManager.LocationChanged += LocationChanged;
            isFirstLoad = false;
        }
    }

    protected override async Task OnInitializedAsync()
    {
        await Refresh();
    }


    public void OnPreEdit(bool value)
    {
        Model.IsEdit = value;
        StateHasChanged();

    }

    protected async Task Refresh()
    {
        try
        {
            isReady = false;
            isNotFound = false;
            //获取周边信息
            Model = await _dataCatcheService.PeripheryIndexPageCatche.GetCache(Id);
            //判断周边名称是否为空 为空则跳转到主页
            if (string.IsNullOrWhiteSpace(Model.Name))
            {
                NavigationManager.NavigateTo("/home");
            }

            isReady = true;

            var user = await authenticationStateTask;

            if (user.User.Identity.IsAuthenticated)
            {
                IsAdmin = user.User.IsInRole("Editor");
            }
        }
        catch (Exception exc)
        {
            isReady = true;
            isNotFound = true;
            StateHasChanged();
        }

    }

    public void CollectionChanged(bool isCollected)
    {
        if (peripheryOverViewTip != null)
        {
            peripheryOverViewTip.CollectionChanged(isCollected, Model.Id);
        }
        if (appPeripheryOverViewTip != null)
        {
            appPeripheryOverViewTip.CollectionChanged(isCollected, Model.Id);
        }
    }

    private async Task OnRevoke(Operation operation)
    {
        var ret = await PopupService.ConfirmAsync("确认撤销编辑", "撤销编辑后会删除数据，无法恢复，请谨慎操作");

        if (ret == false)
        {
            return;
        }
        //上传
        try
        {
            var obj = await _httpService.PostAsync<RevokeExamineModel, Result>("api/peripheries/RevokeExamine", new RevokeExamineModel { Id = Model.Id, ExamineType = operation });
            //判断结果
            if (obj.Successful == false)
            {
                await PopupService.ToastErrorAsync("撤销审核请求失败", obj.Error);
            }
            else
            {
                await PopupService.ToastSuccessAsync("撤销审核请求成功", "撤销审核请求成功");
                //修改各部分编辑状态
                switch (operation)
                {
                    case Operation.EditPeripheryMain:
                        Model.MainState = EditState.Normal;
                        break;
                    case Operation.EditPeripheryImages:
                        Model.ImagesState = EditState.Normal;
                        break;
                    case Operation.EditPeripheryRelatedEntries:
                        Model.RelatedEntriesState = EditState.Normal;
                        break;
                    case Operation.EditPeripheryRelatedPeripheries:
                        Model.RelatedPeripheriesState = EditState.Normal;
                        break;
                }
                await Refresh();
            }
        }
        catch (Exception ex)
        {
            await ErrorHandler.ProcessError(ex, "撤销审核请求失败");
        }
    }
    public async void LocationChanged(object sender, LocationChangedEventArgs args)
    {
        if (Id != Model.Id.ToString())
        {
            if (_dataCatcheService.VideoIndexPageCatche.Check(Id) == false)
            {
                isLoading = true;
                StateHasChanged();
                await Refresh();
                isLoading = false;
                StateHasChanged();
            }
            else
            {
                await Refresh();
                StateHasChanged();
            }

        }
    }

    #region 释放实例

    public void Dispose()
    {

        NavigationManager.LocationChanged -= LocationChanged;

        GC.SuppressFinalize(this);
    }
    #endregion
}
